package com.example.fengyungo_user.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.fengyungo_user.R;
import com.example.fengyungo_user.adapter.MessageListAdapter;
import com.example.fengyungo_user.constant.MessageConstant;
import com.example.fengyungo_user.domain.MessageList;
import com.example.fengyungo_user.domain.User;
import com.example.fengyungo_user.utils.BitmapUtils;
import com.example.fengyungo_user.utils.OkHttpUtils;
import com.example.fengyungo_user.utils.OssUtils;
import com.example.fengyungo_user.utils.ThreadPoolUtil;
import com.example.fengyungo_user.utils.UserUtils;

import java.io.IOException;
import java.util.List;

/**
 * 消息列表 页面
 * @author XLR
 */
public class MessageFragment extends Fragment {

    private static final String TAG = "MessageFragment";

    /**
     * 用户信息
     */
    User user;
    /**
     * 消息列表
     */
    List<MessageList> messageLists;
    /**
     * RecyclerView
     */
    RecyclerView recyclerView;
    /**
     * LinearLayoutManager
     */
    LinearLayoutManager layoutManager;
    /**
     * MessageListAdapter
     */
    MessageListAdapter adapter;
    /**
     * ProgressBar
     */
    ProgressBar progressBar;
    /**
     * 下拉刷新
     */
    SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 广播接收器
     */
    ChatMessageReceiver chatMessageReceiver;
    /**
     * 对本地广播接收器进行管理用
     */
    LocalBroadcastManager localBroadcastManager;

    /**
     * 聊天信息广播接收器
     */
    class ChatMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra(MessageConstant.MESSAGE);
            Log.d(TAG, "onReceive: message=" + message);

            JSONObject jsonObject;
            String content;
            String senderId;

            jsonObject = JSON.parseObject(message);
            content = jsonObject.getString(MessageConstant.CONTENT);
            // 发送者（用户）id
            senderId = jsonObject.getString(MessageConstant.SENDER_ID);
            String sendTime = jsonObject.getString(MessageConstant.SEND_TIME);
            // 找到messageLists中userId为sendId的用户，更新其信息
            int size = messageLists.size();
            MessageList messageList;
            int i;
            for (i = 0; i < size; i++) {
                messageList = messageLists.get(i);
                if (messageList.getUserId().equals(senderId)) {
                    // 更新最新消息的内容与日期和未读消息数
                    messageList.setLastTime(sendTime.substring(5, 10));
                    messageList.setLastContent(content);
                    int lastUserUnread = messageList.getUserUnread();
                    messageList.setUserUnread(lastUserUnread + 1);
                    Log.d(TAG, "onReceive: messageList:"+messageList);
                    break;
                }
            }
            // 刷新recyclerview
            adapter.refreshPartItem(i);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message,container,false);
        // TODO: 2023/12/29 从聊天界面返回到这个界面，要将对应未读消息数清零

        localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());

        // 动态注册广播，动态注册的广播接收器要记得取消注册
        Log.d(TAG, "onCreate: registerReceiver");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("webSocketService");
        chatMessageReceiver = new MessageFragment.ChatMessageReceiver();
        localBroadcastManager.registerReceiver(chatMessageReceiver, intentFilter);

        progressBar = view.findViewById(R.id.progress_bar);
        swipeRefreshLayout = view.findViewById(R.id.refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getMessageList();
                swipeRefreshLayout.setRefreshing(false);
                // 将头像存SharedPreference中
                saveAvatarToSharedPreferences();
            }
        });

        // 获取用户信息
        user = UserUtils.getUserInfo(getActivity());
        Log.d(TAG, "onCreateView: user:" + user);

        recyclerView = view.findViewById(R.id.recyclerview_message_list);

        // 获取用户的消息列表
        getMessageList();

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 动态注册的广播接收器要记得取消注册
        localBroadcastManager.unregisterReceiver(chatMessageReceiver);
    }


    /**
     * 将头像存SharedPreference中
     */
    private void saveAvatarToSharedPreferences() {
        Runnable runnable = () -> {
            for (MessageList messageList : messageLists) {
                Log.d(TAG, "saveAvatarToSharedPreferences: messageList=" + messageList);
                String driverAvatar = messageList.getDriverAvatar();
                Bitmap bitmapFromOss = null;
                if (OkHttpUtils.isValidUrl(driverAvatar)) {
                    bitmapFromOss = OssUtils.getBitmapFromOss(getActivity(), driverAvatar);
                } else {
                    Log.d(TAG, "saveAvatarToSharedPreferences: notInvalidUrl");
                }
                Log.d(TAG, "saveAvatarToSharedPreferences: bitmapFromOss=" + bitmapFromOss);
                if (bitmapFromOss == null) {
                    bitmapFromOss = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
                }
                BitmapUtils.saveBitmapToSharedPreferences(bitmapFromOss, getActivity(), messageList.getDriverId());
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 获取用户的消息列表
     */
    private void getMessageList() {
        String url = MessageConstant.URL + "/user/" + user.getUserId();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    String responseData = OkHttpUtils.get(url);
                    Log.d(TAG, "run: responseData" + responseData);

                    messageLists = UserUtils.parseMessageListJsonWithJsonObject(responseData);
                    Log.d(TAG, "run: messageLists:" + messageLists);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.GONE);
                            layoutManager = new LinearLayoutManager(getActivity());
                            recyclerView.setLayoutManager(layoutManager);
                            adapter = new MessageListAdapter(messageLists);
                            recyclerView.setAdapter(adapter);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

}
